package com.cndym.utils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.codehaus.jackson.type.TypeReference;

import com.cndym.cache.XMemcachedClientWrapper;
import com.cndym.exception.CndymException;
import com.cndym.exception.ErrCode;

public class TaskUtils {

	private static Logger logger = Logger.getLogger(TaskUtils.class);
	
	/**
	 * 发送用户行为串到任务系统
	 * @param msg 请求map
	 * @param body 返回map
	 * @param userCode 用户code
	 */
	public static void sendMessageToTask(final Map<String, String> msg, final Map<String, String> body, final String userCode) {
		new Thread(new Runnable() {
	        @Override
	        public void run() {
//	        	// 将请求消息与处理结果经JMS发送至任务系统
//				GateWayTaskMessageProducer gtm = (GateWayTaskMessageProducer) SpringUtils.getBean("gateWayTaskMessageProducer");
//				Map<String, Object> map;
//	            //发送任务串内判断是否是缓存用户
//		        if(Utils.isNotEmpty(userCode)){
//		        	map = sentTaskIniLogin(userCode);
//			        if(Utils.isNotEmpty(map)){
//						gtm.sendMessage(map);
//			        }
//		        }
//		        if("0000".equals(body.get("code"))){
//		        	map = new HashMap<String, Object>();
//					map.put("msg", msg);
//					map.put("result", body);
//					gtm.sendMessage(map);
//		        }
	        }
	    }).start();
	}
	
	private static Map<String, Object> sentTaskIniLogin(String userCode){

		XMemcachedClientWrapper memcachedClientWrapper = (XMemcachedClientWrapper) SpringUtils.getBean("xmemcachedClientWrapper");
		//判断是否已经发送过登录请求
        String temCode = memcachedClientWrapper.get("LOGIN_USERCODE_"+userCode+"_"+Utils.formatDate2Str(new Date(), "yyyyMMdd"));
        if(Utils.isEmpty(temCode)){
        	//发送登录请求并保存到缓存中
        	memcachedClientWrapper.set("LOGIN_USERCODE_"+userCode+"_"+Utils.formatDate2Str(new Date(), "yyyyMMdd"), 60 * 1440, userCode); //存放多少秒
        	//模拟用户行为数据
    		String mgsTem = "{\"cmd\":\"3101\",\"code\":\"0000\",\"msg\":\"{\\\"userCode\\\":\\\""+userCode+"\\\"}\",\"func\":\"\",\"sysVer\":\"web\",\"softVer\":\"2.0\"}";
    		Map<String, String> msgTem = null;
    		try {
    			msgTem = JsonBinder.buildNormalBinder().getMapper().readValue(mgsTem, new TypeReference<Map<String, String>>() {});
    		} catch (Exception e) {
    			logger.error("发送模拟用户json出现异常", e);
                throw new CndymException(ErrCode.E3002);
    		} 
    		Map<String, Object> map = new HashMap<String, Object>();
    		map.put("msg", msgTem);
    		map.put("result", msgTem);
    		return map;
        }
        return null;
	}
}
